package com.medvalley.tcm.controller;

import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.service.impl.AliOSSService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author linsong
 * @date 2019/4/21 15:46
 **/
@RestController
@Api("上传图片接口")
@RequestMapping("/file")
public class OssController extends BaseController {

    private static Logger LOGGER = LoggerFactory.getLogger(OssController.class);

    @Value("${oss.physician-accreditation.bucketName}")
    private String physicianBucketName;

    @Autowired
    private AliOSSService aliOSSService;

    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result uploadHeadIcon(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String suffix = "";
            if (fileName.lastIndexOf(".") > 0) {
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            long currentTime = System.currentTimeMillis();
            String uri = aliOSSService.upload(file.getInputStream(), "file-" + currentTime + suffix, physicianBucketName);
            return success(uri);
        } catch (IOException e) {
            LOGGER.error("上传错误", e);
            return error("上传错误");
        }
    }

}
